package at.fhhgb.mc.android.mfb_hgb.dal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import at.fhhgb.mc.android.mfb_hgb.control.JSONParser;
import at.fhhgb.mc.android.mfb_hgb.model.Offer;
import at.fhhgb.mc.android.mfb_hgb.model.TaskCaller;

public class SelectOffer extends AsyncTask<NameValuePair, Void, List<Offer>> {
	private JSONParser jParser = new JSONParser();
	private TaskCaller caller;
	
	private static final String URL_SELECT_OFFER = "http://jupuuu.funpic.de/mySQL/select_offer.php";
	
	/**
	 * Default constructor
	 * @param caller The caller of AsyncTask
	 */
	public SelectOffer(TaskCaller caller)
	{
		this.caller = caller;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	// Getting Users for parameters
	@Override
	protected List<Offer> doInBackground(NameValuePair... params)  {		
		// getting JSON string from URL
		JSONObject json = jParser.makeHttpRequest(URL_SELECT_OFFER, "GET", Arrays.asList(params));

		try {
			// Checking for SUCCESS TAG
			int success = json.getInt("success");

			if (success == 1) {
				// Users found
				// Getting Array of Users
				JSONArray data = json.getJSONArray("offers");
				List<Offer> result = new ArrayList<Offer>();
				
				// looping through All Users
				for (int i = 0; i < data.length(); i++) {
					JSONObject c = data.getJSONObject(i);
					
					// Result to User-Object
					Offer offer = new Offer(c.getLong("OfferID"), c.getString("Name"), c.getInt("Type"), c.getString("Source"), c.getString("Destination"), c.getString("Over"), c.getString("DepartureFrom"), c.getString("DepartureTo"), c.getString("Note"));
					result.add(offer);
				}
				
				return result;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * After completing background task
	**/
	@Override
	protected void onPostExecute(List<Offer> result) {
		caller.onBackgroundTaskCompleted(result);
	}
}
